const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // CSS抽取单独文件
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); // 压缩Css
const EslintWebpackPlugin = require("eslint-webpack-plugin"); // ESlint检查
const CopyPlugin = require("copy-webpack-plugin"); // 复制文件或目录插件

module.exports = {
  entry: "./src/index.tsx",
  output: {
    path: path.resolve(__dirname, "../dist"),
    filename: "js/[name].[contenthash:6].js",
    chunkFilename: "js/[name].chunk.[contenthash:6].js",
    clean: true
  },
  mode: "production",
  devtool: "source-map",
  module: {
    rules: [
      {
        test: /\.(j|t)sx?$/,
        include: path.resolve(__dirname, "../src"), // 只处理src下的文件
        use: [
          {
            loader: "babel-loader",
            options: {
              cacheDirectory: true, // 开启babel缓存
              cacheCompression: false // 关闭缓存压缩
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "less-loader"]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "ReactWebpackTS",
      template: "./public/index.html"
    }),
    new MiniCssExtractPlugin({
      filename: "css/[name].[contenthash:6].css",
      chunkFilename: "css/[name].chunk.[contenthash:6].css"
    }),
    new EslintWebpackPlugin({
      context: "./src", // 指定文件目录
      exclude: "node_modules", // 默认值
      extensions: ["ts", "tsx"], // 检查的文件名，默认为js
      cache: true, // 开启eslint缓存
      cacheLocation: path.resolve(__dirname, "../node_modules/.cache/eslintcache") // 缓存目录
    }),
    new CopyPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, "../public"),
          to: path.resolve(__dirname, "../dist"),
          globOptions: {
            ignore: ["**/index.html"]
          }
        }
      ]
    })
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "../src")
    },
    extensions: [".tsx", ".ts", ".js"]
  },
  optimization: {
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        // react react-dom等一起打包成一个js文件
        react: {
          test: /[\\/]node_modules[\\/]react(.*)[\\/]/,
          name: "react-chunk",
          priority: 40
        },
        // antd单独打包
        antd: {
          test: /[\\/]node_modules[\\/]antd[\\/]/,
          name: "antd-chunk",
          priority: 30
        },
        // 剩下的node_modules打包
        libs: {
          test: /[\\/]node_modules[\\/]/,
          name: "libs-chunk",
          priority: 20
        }
      }
    },
    minimizer: [
      "...", // js压缩
      new CssMinimizerPlugin() // 压缩css
    ],
    // 为入口文件添加hash值映射rumtime文件，chunk变化这个文件变化而main不会变化
    runtimeChunk: {
      name: entrypoint => `runtime~${entrypoint.name}.js`
    }
  },
  performance: false // 关闭性能分析，提升打包速度
};
